package com.bjb.vr.auth.filter;

import cn.hutool.core.codec.Base64;
import com.bjb.vr.auth.exception.CaptchaNotMatchException;
import com.bjb.vr.auth.exception.UserAccountInvaildException;
import com.bjb.vr.auth.util.AccessRequestUtil;
import com.bjb.vr.common.constant.CaptchaConstants;
import com.bjb.vr.common.constant.ThreadLocalConstant;
import com.bjb.vr.common.utils.RedisUtil;
import com.bjb.vr.common.utils.ThreadLocalUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Objects;

/**
 * 登录认证过滤器
 *
 * @version 1.0.0
 * @author: HuJingBo
 * @time: 2022/4/8 16:43
 */
@Slf4j
public class CustomLoginFilter extends UsernamePasswordAuthenticationFilter {

    private final static String POST_METHOD_PARAMETER = "POST";
    private final static String CAPTCHA_KEY_PARAMETER = "captchaKey";
    private final static String CAPTCHA_VALUE_PARAMETER = "captchaValue";
    private RedisUtil redisUtil;
    private Boolean enableCaptcha;

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) {

        // 判断是否是 post 方式请求
        if (!request.getMethod().equals(POST_METHOD_PARAMETER)) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 判断是否是 json 格式请求类型
        if (!request.getContentType().equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            throw new AuthenticationServiceException("Authentication MediaType not supported: " + request.getContentType());
        }

        try {
            // 获取请求参数
            Map<String, String> parameters = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            String host = AccessRequestUtil.takeHeaders().get(ThreadLocalConstant.USER_HOST);
            parameters.put(ThreadLocalConstant.USER_HOST, host);
            ThreadLocalUtil.set(ThreadLocalConstant.REQUEST_BODY, parameters);
            String username = parameters.get(getUsernameParameter());
            String password = Base64.decodeStr(parameters.get(getPasswordParameter()));
            String captchaKey = parameters.get(CAPTCHA_KEY_PARAMETER);
            String captchaValue = parameters.get(CAPTCHA_VALUE_PARAMETER);
            String loginType = parameters.get(ThreadLocalConstant.LOGIN_TYPE);

            // 校验请求参数
            verifyAuthentication(username, password, captchaKey, captchaValue, loginType);

            // 放行SQL拦截,允许通过
            ThreadLocalUtil.set(ThreadLocalConstant.NO_TENANT_ID_VERIFY, true);
            ThreadLocalUtil.set(ThreadLocalConstant.LOGIN_TYPE, loginType);

            // 校验用户名密码
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request, authentication);
            // 设置用户信息
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return this.getAuthenticationManager().authenticate(authentication);
        } catch (Exception e) {
            throw new UserAccountInvaildException(e.getMessage());
        }
    }

    /**
     * 校验请求参数
     *
     * @return
     */
    private void verifyAuthentication(String username, String password, String captchaKey, String captchaValue, String loginType) {
        // 判断用户名密码是否为空
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new AuthenticationServiceException("用户名或密码不能为空");
        }

        // 判断登录端的类型是否为空
        if (StringUtils.isBlank(loginType)) {
            throw new AuthenticationServiceException("登录端类型不能为空");
        }

        if (enableCaptcha) {
            // 判断验证码是否为空
            if (StringUtils.isBlank(captchaKey) || StringUtils.isBlank(captchaValue)) {
                throw new CaptchaNotMatchException("验证码不能为空");
            }

            // 校验验证码-是否过期
            String captchaCacheValue = (String) redisUtil.hget(CaptchaConstants.LOGIN_CAPTCHA_KEY + captchaKey, CaptchaConstants.CAPTCHA_VALUE);
            if (StringUtils.isBlank(captchaCacheValue)) {
                throw new CaptchaNotMatchException("验证码已过期");
            }

            // 校验验证码-是否匹配
            if (!Objects.equals(captchaCacheValue, captchaValue)) {
                throw new CaptchaNotMatchException("验证码错误");
            }
        }
    }

    public void setRedisService(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public void setEnableCaptcha(Boolean enableCaptcha) {
        this.enableCaptcha = enableCaptcha;
    }

}
